package vip.xumy.core.utils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import vip.xumy.core.exception.CoreException;
import vip.xumy.core.golbal.GlobalConstant;

/**	All rights reserved
 *	author:mengyxu
 *	date:2019年5月25日
 */

public class Base64Util {

	/**
	 * 解密
	 * @return
	 * @throws CoreException 
	 */
	public static String decodeToString(String str) throws CoreException {
		return decodeToString(str, GlobalConstant.ENCODING_UTF8);
	}
	
	public static byte[] decode(String str) {
		return Base64.getDecoder().decode(str);
	}
	
	public static String decodeToString(String str, String encoding) throws CoreException{
		try {
			byte[] decode = decode(str);
			return new String(decode, encoding);
		} catch (UnsupportedEncodingException e) {
			throw new CoreException("Unsupport encoding [" + encoding +"]", e);
		}catch (IllegalArgumentException e) {
			throw new CoreException("It's not the Base64 encoding string.");
		}
		
	}

	/**
	 * 加密
	 * @return
	 * @throws CoreException 
	 */
	public static String encode(String str) throws CoreException {
		return encode(str.getBytes());
	}
	
	public static String encode(byte[] bytes) {
		return Base64.getEncoder().encodeToString(bytes);
	}
	
	public static String encode(String str, String encoding) throws CoreException {
		try {
			return encode(str.getBytes(encoding));
		} catch (UnsupportedEncodingException e) {
			throw new CoreException("Unsupport encoding [" + encoding +"]", e);
		}
	}
	
	private Base64Util(){}
}
